# -*- coding: UTF-8 -*- #
"""
-------真正的勇士， 敢于直面惨淡的Warning、 敢于正视淋漓的Error-----
@author : 贾鹏博
@file : base_page.py
@time : 2022/6/15 22:10
"""

from selenium.common.exceptions import NoSuchElementException
from apptest.QiYeWeiXin_PO.utils.Logger import *
from appium.webdriver.webdriver import WebDriver
from appium.webdriver.common.appiumby import AppiumBy


# 实例化 driver 、 查找元素 、 滑动等
class BagePage:
    implicitly_wait_time = 30

    def __init__(self, driver: WebDriver = None):
        """初始化"""
        self.driver = driver

    def swipe_find(self, txt, num=3):
        """滑动查找"""
        self.set_implicitly(1)
        for i in range(num):
            try:
                # 自定义查找
                element = self.find(AppiumBy.XPATH, "//*[@text='{text}']")
                self.set_implicitly(self.implicitly_wait_time)
                return element
            except:
                logger.info('未找到元素，开始滑动')
                # 获取当前屏幕尺寸，返回一个字典
                self.swipe_up()
            if i == num - 1:
                self.set_implicitly(self.implicitly_wait_time)
                raise NoSuchElementException(f'找了{num}次，未找到元素{txt}')

    def swipe_up(self):
        """向上滑动"""
        size = self.get_windows_size()
        width = size.get('width')
        height = size.get('height')
        logger.info(f'获取的宽{width},高{height}')
        start_x = width / 2
        start_y = height * 0.8
        end_x = start_x
        end_y = height * 0.3
        duration = 2000
        logger.info(f'开始滑动:{start_x},{start_y} to {end_x},{end_y}')
        self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def get_windows_size(self):
        """获取屏幕的的尺寸"""
        return self.driver.get_window_size()

    def find(self, by, locator):
        """查找元素"""
        logger.info(f"正在定位元素{locator}")
        return self.driver.find_element(by, locator)

    def finds(self, by, locator):
        return self.driver.find_elements(by, locator)

    def set_implicitly(self, time_):
        """设置隐式等待时长"""
        self.driver.implicitly_wait(time_)

    def find_and_click(self, by, locator):
        self.find(by, locator).click()

    def find_and_send(self, by, locator, text):
        self.find(by, locator).send_keys(text)

    def get_toast_text(self):
        """获取 toast 文本"""
        toast_text = self.find(AppiumBy.XPATH, "//*[@class='android.widget.Toast']").text
        return toast_text

    def back(self, num=1):
        """返回操作"""
        for i in range(num):
            self.driver.back()
